/*
 * @(#) UploadAction.java 2014年7月20日
 *
 * Copyright (c) 2014, SIMPO Technology. All Rights Reserved.
 * SIMPO Technology. CONFIDENTIAL
 */
package com.thinkgem.jeesite.modules.tdc.visitor.web;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.tdc.visitor.service.TdcVisitorReservationService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 *  文件上传
 */
@Controller
@RequestMapping(value = "/visitorUpload")
public class FileUploadAction {

    /*允许上传的图片文件类型*/
    protected final static String[] imgFileType = new String[]{".jpg", ".gif", ".bmp", ".png", ".jpeg"};
    /*允许上传的视频文件类型*/
    protected final static String[] videoFileType = new String[]{".rmvb", ".avi", ".mp4", ".flv"};
    /*允许上传的文档类型*/
    protected final static String[] docFileType = new String[]{".txt", ".doc", ".docx", ".xls", ".xlsx"};
    protected final static String[] excelFileType = new String[]{ ".xls", ".xlsx"};
    /*允许上传的其他文件类型*/
    protected final static String[] otherFileType = new String[]{".rar", ".zip", ".7z", ".apk"};
    private final static String IMAGE_TYPE = "1";
    private final static String VIDEO_TYPE = "2";
    private final static String DOC_TYPE = "3";
    private final static String EXCEL_TYPE = "5";
    /*正式环境地址*/
    public static final String images = "/uploads/pc/images/";
    public static final String images_thumb = "/uploads/phone/thumb/";
    public static final String videos = "/uploads/pc/videos/";
    public static final String docs = "/uploads/pc/docs/";
    public static final String other = "/uploads/pc/files/";

   

    /**
     * 图片文件上传
     *
     * @param request
     * @param response
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadImageFile", method = {RequestMethod.POST}, produces = MediaType.TEXT_HTML_VALUE)
    public
    @ResponseBody
    void uploadImageFile(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) {
    	String out = "";
    	/*返回状态码 或 图片名*/
        String originalFilename = file.getOriginalFilename();
        /*图片太大，请上传小于5M的图片*/
        if(request.getContentLength() > 5120000){
        	out = "1003";
        }else if (!StringUtils.isEmpty(originalFilename) && originalFilename.lastIndexOf(".") > 0) {
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".")); //文件扩展名
            if (isExit(ext, IMAGE_TYPE) == false) {
            	/*图片格式不正确*/
            	out = "1002";
            }else{
            	
            /*附件名形如：suspectAttachmenta02b032f05e6453a9ed1f71696ff5f0e.jpg
            		   bespeakCredentialsa02b032f05e6453a9ed1f71696ff5f0e.jpg*/
//            	String realFilename = request.getParameter("who") + request.getParameter("bespeakId") + ext;
            	/*如果重新上传，删除旧文件*/
            	String oldFilename = request.getParameter("fileName");
            	if(null != oldFilename && !"".equals(oldFilename)){
            		oldFilename = "/userfiles" +oldFilename.split("userfiles")[1];
	            	File oldFile = new File(request.getSession().getServletContext().getRealPath(oldFilename));
	            	if(oldFile.exists())oldFile.delete();
            	}
                
            	String realFilename = IdGen.uuid() + ext;
            	String pathyyyymm = "/userfiles/1/images/imagesAttachment/" + TdcVisitorReservationService.yyyymm();
            	String realPath = request.getSession().getServletContext().getRealPath(pathyyyymm);
            	try {
//            		String path = realPath + realFilename;// 图片路径
//            		String thumbPath = thumb + realFilename; // 缩略图 路径
            		saveFile(file.getInputStream(), realPath, realFilename);
            		/*保存成功，返回json数据：附件相对路径+附件名*/
            		out = "{\"name\":\""+(request.getContextPath()+pathyyyymm+realFilename)+"\"}";
            		
//				File dir = new File(thumb);
//				if (!dir.exists()) {
//					dir.mkdirs();
//				}
//                // 缩略图处理
//				ImageUtil.saveMinPhoto(path, thumbPath, 139, 0.9d);
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
            }
        }else out = "1001";/*系统上传错误*/
        try {
        	 response.setContentType("text/html");
			response.getWriter().println(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 判断类型是否符合限制要求
     *
     * @param ext
     * @param type
     * @return
     * @author liq
     * @since: 2015年7月21日
     */
    public boolean isExit(String ext, String type) {
    	/*图片类型*/
        if (IMAGE_TYPE.equals(type)) {
            for (int i = 0; i < imgFileType.length; i++) {
                if (ext.equalsIgnoreCase(imgFileType[i])) {
                    return true;
                }
            }
            return false;
        } else if (VIDEO_TYPE.equals(type)) {
            for (int i = 0; i < videoFileType.length; i++) {
                if (ext.equalsIgnoreCase(videoFileType[i])) {
                    return true;
                }
            }
            return false;
        } else if (DOC_TYPE.equals(type)) {
            for (int i = 0; i < docFileType.length; i++) {
                if (ext.equalsIgnoreCase(docFileType[i])) {
                    return true;
                }
            }
            return false;
        }else if(EXCEL_TYPE.equals(type)){
            for (int i = 0; i < excelFileType.length; i++) {
                if (ext.equalsIgnoreCase(excelFileType[i])) {
                    return true;
                }
            }
            return false;
        } else {
            for (int i = 0; i < otherFileType.length; i++) {
                if (ext.equalsIgnoreCase(otherFileType[i])) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 保存上传的文件在project目录下
     *
     * @param stream
     * @param path
     * @param filename
     * @throws IOException
     */
    private void saveFile(InputStream stream, String path, String filename) throws IOException {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(path + "\\" + filename);
        /*如果不存在，创建*/
        if (!file.exists()) {
            file.createNewFile();
        }
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        FileOutputStream fs = new FileOutputStream(path + "\\" + filename);
        while ((byteread = stream.read(buffer)) != -1) {
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }
    

}
